package com.holly.unit.deform.util;

import java.io.IOException;
import java.io.Reader;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 类描述: 表单数据工具类
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/4/12 9:35
 */
public class FormDataUtil {

    /**
     * map的key转成小写
     * @param orgMap
     * @return
     */
    public static Map<String, Object> transLowerCaseMapKey(Map<String, Object> orgMap){
        Map<String, Object> resultMap = new HashMap<>();
        if (orgMap == null || orgMap.isEmpty()) {
            return resultMap;
        }
        Set<String> keySet = orgMap.keySet();
        for (String key : keySet) {
            //update-begin--Author:scott  Date:20190926 for：TASK #3210 【数据库兼容bug】oracle下大字段报错------------------
            //clob字段处理
            Object val = orgMap.get(key);
            if (val instanceof Clob) {
                val = Clob2String((Clob) val);
            }else if(val instanceof byte[]){
                val = new String((byte[])val);
            }else if (val instanceof Blob) {
                try {
                    if (val != null) {
                        Blob val_b = (Blob) val;
                        val = new String(val_b.getBytes(1, (int) val_b.length()), "UTF-8");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            String newKey = key.toLowerCase();
            resultMap.put(newKey, val);
            //update-end--Author:scott  Date:20190926 for：TASK #3210 【数据库兼容bug】oracle下大字段报错------------------
        }
        return resultMap;
    }

    /**
     * Clob字段转String
     * @param clob
     * @return
     */
    public static String Clob2String(Clob clob) {
        String clobStr = "";
        try {
            Reader inStream = clob.getCharacterStream();
            char[] c = new char[(int) clob.length()];
            inStream.read(c);
            clobStr = new String(c);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return clobStr;
    }

}
